package com.supermarket.user.service.impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.supermarket.common.core.domain.R;
import com.supermarket.common.core.utils.StringUtils;
import com.supermarket.common.core.web.domain.AjaxResult;
import com.supermarket.order.api.RemoteOrderService;
import com.supermarket.order.api.domain.OrderById;
import com.supermarket.user.domain.*;
import com.supermarket.user.domain.dto.IntegralDto;
import com.supermarket.user.domain.dto.UserDto;
import com.supermarket.user.domain.vo.UserDetailVo;
import com.supermarket.user.domain.vo.UserVo;
import com.supermarket.user.mapper.*;
import com.supermarket.user.service.MemberLevelService;
import com.supermarket.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RemoteOrderService remoteOrderService;
    @Autowired
    private UserMapStructMapper userMapStructMapper;
    @Autowired
    private UserTagMapper userTagMapper;
    @Autowired
    private IntegralRecordMapper integralRecordMapper;
    @Autowired
    private MemberLevelService memberLevelService;
    @Autowired
    private UserCouponMapper userCouponMapper;
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private CouponMapper couponMapper;
    /**
     * 客户列表
     *
     * @param userDto
     * @return
     */
    @Override
    public List<UserVo> list(UserDto userDto) {
        // 查询用户列表
        List<User> userList = userMapper.list(userDto);
        if (CollectionUtils.isEmpty(userList)) {
            return Collections.emptyList();
        }

        // 提取用户ID列表
        List<Long> userIds = userList.stream()
                .map(User::getId)
                .collect(Collectors.toList());

        // 批量远程调用获取订单信息
        Map<Long, List<OrderById>> orderMap = fetchOrderMapByUserIds(userIds);

        // 转换用户列表并填充订单信息
        return userList.stream()
                .map(user -> {
                    UserVo userVo = userMapStructMapper.INSTANCE.toUserVo(user);
                    fillOrderInfo(userVo, orderMap.getOrDefault(user.getId(), Collections.emptyList()));
                    return userVo;
                })
                .collect(Collectors.toList());
    }

    // 批量获取订单信息的方法
    private Map<Long, List<OrderById>> fetchOrderMapByUserIds(List<Long> userIds) {
        try {
            // 根据用户ids批量获取订单信息
            R<Map<Long, List<OrderById>>> result = remoteOrderService.getOrderMapByUserIds(userIds);
            if (result != null && result.getCode() == 200 && result.getData() != null) {
                return result.getData();
            }
        } catch (Exception e) {
            log.error("批量获取用户订单信息失败, userIds={}" + userIds, e);
            // 这里可以根据业务需求决定是返回空Map还是抛出异常
        }
        return Collections.emptyMap();
    }

    // 填充订单相关信息
    private void fillOrderInfo(UserVo userVo, List<OrderById> orderList) {
        if (CollectionUtils.isEmpty(orderList)) {
            // 无订单信息
            userVo.setLatestConsumptionTime(null);
            userVo.setLatestConsumptionPrice(BigDecimal.ZERO);
            userVo.setAccumulationConsumptionCount(0);
            userVo.setAccumulationConsumptionPrice(BigDecimal.ZERO);
            return;
        }

        // 对订单按创建时间排序
        List<OrderById> sortedOrders = orderList.stream()
                .sorted(Comparator.comparing(OrderById::getCreateTime).reversed())
                .collect(Collectors.toList());

        // 累计消费次数
        userVo.setAccumulationConsumptionCount(sortedOrders.size());

        // 累计消费金额
        BigDecimal totalAmount = sortedOrders.stream()
                .map(OrderById::getPayAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        userVo.setAccumulationConsumptionPrice(totalAmount);

        // 最后一次消费信息
        OrderById latestOrder = sortedOrders.get(0);
        userVo.setLatestConsumptionTime(latestOrder.getCreateTime());
        userVo.setLatestConsumptionPrice(latestOrder.getPayAmount());
    }

    /**
     * 添加用户标签
     * @param tagIds
     * @param userIds
     * @return
     */
    @Override
    public AjaxResult setTag(String tagIds, String userIds) {
        if(StringUtils.isEmpty(tagIds)){
            return AjaxResult.error("请选择标签");
        }
        if(StringUtils.isEmpty(userIds)){
            return AjaxResult.error("请选择用户");
        }
        //先删除用户有的标签
        userTagMapper.deleteUserTag(userIds);
        //给用户添加所选的标签
        String[] userIDArray = userIds.split(",");
        String[] tagIdList = tagIds.split(",");
        List<String> tagId = new ArrayList<>();
        tagId.addAll(Arrays.asList(tagIdList));
        for (String userId : userIDArray) {
            userTagMapper.addUserTag(userId,tagId);
        }
        return AjaxResult.success();
    }

    /**
     * 修改用户积分
     * @param integralDto
     * @return
     */
    @Override
    public AjaxResult updateIntegral(IntegralDto integralDto) {
        if(integralDto.getIntegral() == null){
            return AjaxResult.error("请输入积分");
        }
        //创建积分记录表
        IntegralRecord integralRecord = new IntegralRecord();
        //获取用户积分
        User user = userMapper.selectById(integralDto.getUserId());
        //判断用户积分是否大于修改的积分
        if(user.getIntegral() > integralDto.getIntegral()){
            //用户变化的积分
            integralRecord.setChange(user.getIntegral() - integralDto.getIntegral());
            //积分类型0添加1扣减
            integralRecord.setTypeId(1);
        }else{
            //用户变化的积分
            integralRecord.setChange(integralDto.getIntegral() - user.getIntegral());
            //积分类型0添加1扣减
            integralRecord.setTypeId(0);
        }
        integralRecord.setUserId(integralDto.getUserId());
        integralRecord.setAfterIntegral(integralDto.getIntegral());
        integralRecord.setRemark(integralDto.getRemark());
        integralRecordMapper.insert(integralRecord);
        user.setIntegral(integralDto.getIntegral());
        //修改用户积分
        userMapper.updateById(user);
        return AjaxResult.success("添加成功");
    }

    @Override
    public AjaxResult updateLevel(Long userId, Long memberLevelId) {
        //获取用户
        User user = userMapper.selectById(userId);
        //首先获取等级的规则
        MemberLevel memberLevel = memberLevelService.getOne(new QueryWrapper<MemberLevel>().eq("id",memberLevelId));
        if(memberLevel.getMinPoints() > user.getIntegral()){
            return AjaxResult.error("积分不够");
        }
        //修改用户等级
        user.setMemberLevelId(memberLevelId);
        userMapper.updateById(user);
        return AjaxResult.success("修改成功");
    }

    @Override
    public AjaxResult freeze(String userId, String status) {
        //利用StringUtils判空
        if(StringUtils.isEmpty(userId)){
            return AjaxResult.error("请选择用户");
        }
        if(StringUtils.isEmpty(status)){
            return AjaxResult.error("请选择限制的状态");
        }
        //获取用户id
        String[] userIds = userId.split(",");
        //status中有0则限制下单1限制领优惠券2限制评论
        if(status.contains("0")){
            //如果状态中有0则限制下单
            userMapper.updateFreezeOrder(userIds);
        }
        if(status.contains("1")){
            //如果状态中有1则限制领优惠券
            userMapper.updateFreezeCoupon(userIds);
        }
        if(status.contains("2")){
            //如果状态中有2则限制评论
            userMapper.updateFreezeComment(userIds);
        }
        return AjaxResult.success("冻结成功");
    }

    @Override
    public AjaxResult addCoupon(String userIds, String couponIds) {
        //非空校验
        if(StringUtils.isEmpty(userIds)){
            return AjaxResult.error("用户id不能为空");
        }
        if(StringUtils.isEmpty(couponIds)){
            return AjaxResult.error("优惠券id不能为空");
        }
        String[] userIdList = userIds.split(",");
        String[] couponIdList = couponIds.split(",");
        List<String> couponIdsList = new ArrayList<>();
        couponIdsList.addAll(Arrays.asList(couponIdList));
        for (String userId : userIdList) {
            userCouponMapper.addCoupon(userId,couponIdsList);
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult updateUser(User user) {
        this.updateById(user);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult userDetail(Long userId) {
        UserDetailVo userDetailVo = new UserDetailVo();
        //判读用户是否为空
        if (userId == null) {
            return AjaxResult.error("用户ID不能为空");
        }
        User user = this.getById(userId);
        userDetailVo.setUser(user);
        //获取用户所拥有的标签
        List<Tag> tagList = tagMapper.listByUserId(userId);
        userDetailVo.setTagList(tagList);
        //获取用户所拥有的优惠券
        List<Coupon> couponList = couponMapper.listByUserId(userId);
        userDetailVo.setCouponList(couponList);
        //获取用户积分记录
        List<IntegralRecord> integralRecordList = integralRecordMapper.listByUserId(userId);
        userDetailVo.setIntegralRecordList(integralRecordList);
        //远程调用获取用户消费信息
        R<List<OrderById>> orderListById = remoteOrderService.getOrderListById(userId);
        if(orderListById.getCode()!=200){
            return AjaxResult.error(orderListById.getMsg());
        }
        //订单列表
        userDetailVo.setUserOrderList(orderListById.getData());
        return AjaxResult.success(userDetailVo);
    }
}